package controller

import (
	"fmt"
	"ginVueNew/common"
	"ginVueNew/dto"
	"ginVueNew/model"
	"ginVueNew/response"
	"ginVueNew/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Register(ctx *gin.Context){
	// 单纯的下面三行获取不到html传参
	//name := ctx.PostForm("name")
	//telephone := ctx.PostForm("telephone")
	//password := ctx.PostForm("password")


	//方法1
	//var requsetMap = make(map[string]string)
	//json.NewDecoder(ctx.Request.Body).Decode(requsetMap) //将传参的body解析到map

	//方法2
	//var requestUser = model.User{}
	//json.NewDecoder(ctx.Request.Body).Decode(requestUser)
		var requestUser = model.User{}
		ctx.Bind(&requestUser)
		DB := common.GetDB()
		name := requestUser.Name
		telephone := requestUser.Telephone
		password := requestUser.Password
		if len(telephone) != 11{
			response.Response(ctx,http.StatusUnprocessableEntity,422,nil,"手机号长度必须为11位")
			return
		}
		if len(password) <3 {
			response.Response(ctx,http.StatusUnprocessableEntity,422,nil,"密码长度不小于3位")
			return
		}
		if len(name) == 0{
			name = utils.RandomString(13)
		}
		if utils.IsTelephoneExists(DB,telephone){
			response.Response(ctx,http.StatusUnprocessableEntity,422,nil,"用户已经存在")
			return
		}
		hashPwd,err := bcrypt.GenerateFromPassword([]byte(password),bcrypt.DefaultCost)
		if err != nil{
			response.Response(ctx,http.StatusInternalServerError,500,nil,"加密错误")
			return
		}
		user := model.User{
			Telephone: telephone,
			Name: name,
			Password: string(hashPwd),
		}
		DB.Create(&user)
		token,err := common.ReleaseToken(user)
		if err != nil{
			ctx.JSON(http.StatusUnprocessableEntity,gin.H{
				"code":500,
				"msg":"系统异常",
			})
			log.Printf("token generates error: %v",err)
			return
		}
		response.Success(ctx,gin.H{"token":token},"注册成功")
}

func Login(ctx *gin.Context){
	DB := common.GetDB()
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	if len(telephone) != 11{
		fmt.Println("rnm")
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"手机号长度必须为11位",
		})
		return
	}
	if len(password) <6 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"密码长度不小于6位",
		})
		return
	}
	var user model.User
	DB.Where("telephone = ?",telephone).First(&user)
	if user.ID == 0{
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"用户不存在",
		})
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password),[]byte(password));err != nil{
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":400,
			"msg":"密码错误",
		})
		return
	}
	token,err := common.ReleaseToken(user)
	if err != nil{
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":500,
			"msg":"系统异常",
		})
		log.Printf("token generates error: %v",err)
		return
	}
	response.Success(ctx,gin.H{"token":token},"登录成功")
}

func Info(ctx *gin.Context){
	user,_ := ctx.Get("user")
	ctx.JSON(http.StatusOK,gin.H{
		"code":200,
		"user":dto.ToUserDto(user.(model.User)),//类型断言r
	})
}